import store from '../store'
import Pinyin from 'pinyin4js';
import { ref } from 'vue';

// 校验手机正则
export function isphone(data : any) {
	return /^(?!.*(\d)\1{4})[1][3,4,5,6,7,8,9][0-9]{9}$/.test(data)
}

// 获取url参数
export function getParam(scene : any, name : any) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	//search,查询？后面的参数，并匹配正则
	var r = scene.match(reg);
	if (r != null) return decodeURI(decodeURI(r[2]));
}



// // 获取url参数
// export function getParam(name : any) {
// 	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
// 	//search,查询？后面的参数，并匹配正则
// 	var r = location.search.substr(1).match(reg);
// 	if (r != null) return decodeURI(decodeURI(r[2]));
// }





//校验距离
export function mToKm(m : any) {
	let km : any = (m / 1000).toFixed(2);

	if (km < 1) {
		return m + "m";
	} else {
		return km + "km";
	}

	// else if (km > 9999.9) {
	// 	return "9999.99km";
	// } 
}

export function ising(item1, item2) {
	getToday()
}


/* 提示 */
export function showToast(
	title : any,
	icon : any = "none",
	position : any = "bottom",
	duration : any = 1500,
	mask : any = false
) {
	uni.showToast({
		title,
		icon,
		duration,
		position,
		mask,
	});
}


export function timestampToDate(timestamp) {
	const date = new Date(timestamp); // 如果timestamp是数字，直接用于创建Date对象
	const year = date.getFullYear(); // 获取年份
	const month = ('0' + (date.getMonth() + 1)).slice(-2); // 获取月份，转为两位数
	const day = ('0' + date.getDate()).slice(-2); // 获取日，转为两位数
	const hours = ('0' + date.getHours()).slice(-2); // 获取小时，转为两位数
	const minutes = ('0' + date.getMinutes()).slice(-2); // 获取分钟，转为两位数


	return `${year}-${month}-${day} ${hours}:${minutes}`; // 拼接字符串返回
}

//获取当天时间
export function getToday() {
	// 获取当前时间
	let date = new Date();
	let year = date.getFullYear();
	let month = date.getMonth() + 1; //当前月
	let day = date.getDate();
	let newDay = year + "-" + month + "-" + day;

	return newDay;
}

//获取星期几
export const weekDay = function (time : any) {
	let date : any
	if (time.indexOf("-") > -1) {//如果有横杠，就要匹配成/，为了兼容Ios
		date = `${time.split('-')[0]}/${time.split('-')[1]}/${time.split('-')[2]}`
	}

	const weekNum = new Date(date).getDay();
	let week = "";
	switch (weekNum) {
		case 0:
			week = "周日";
			break;
		case 1:
			week = "周一";
			break;
		case 2:
			week = "周二";
			break;
		case 3:
			week = "周三";
			break;
		case 4:
			week = "周四";
			break;
		case 5:
			week = "周五";
			break;
		case 6:
			week = "周六";
			break;
	}
	return week;
};

//当前日期加时间(如:2009-06-12 )
export function dateDiffStr(startDateStr, endDateStr) {
	var day = 0;
	var separator = "-"; //日期分隔符
	var date1 = startDateStr.substring(0, 10).split(separator);
	var date2 = endDateStr.substring(0, 10).split(separator);
	var date11 = new Date(date1[0], date1[1] - 1, date1[2]);
	var date22 = new Date(date2[0], date2[1] - 1, date2[2]);
	day = parseInt(Math.abs(date22 - date11) / (1000 * 60 * 60 * 24));
	return day;
}

export function getDateYearSubNew(startDateStr, endDateStr) {
	// 根据出生日期计算年龄

	var sDate = new Date(Date.parse(startDateStr.replace(/-/g, "/")));
	var eDate = new Date(Date.parse(endDateStr.replace(/-/g, "/")));

	var result = 0;

	//获得各自的年、月、日
	var sY = sDate.getFullYear();
	var sM = sDate.getMonth() + 1;
	var eY = eDate.getFullYear();
	var eM = eDate.getMonth() + 1;

	var yL = eY - sY;
	var mL = eM - sM;

	if (mL < 0) {
		yL--;
	}
	if (yL > 0) {
		result = yL;
	} else {
		result = 0;
	}
	return result;
}

export function GetRequest(url, name) {
	var reg = new RegExp("(^|[&,?])" + name + "=([^&]*)(&|$)", "i");
	var r = url.match(reg);
	if (r != null) return r[2];
	return null;
}


export function getNetwork() {
	let self = this;
	return new Promise((resolve, reject) => {
		uni.getNetworkType({
			success(res) {
				const networkType = res.networkType;
				if (networkType === "none") {
					reject(false);
				} else {
					resolve(true);
				}
			},
		});
	});
}


//节流
export function throttle(fn, delay) {
  let timer = null;
  return function(...args) {
    if (!timer) {
      fn.apply(this, args);
      timer = setTimeout(() => {
        timer = null;
      }, delay);
    }
  }
}

// 防抖
export function debounce(func, delay) {
  let timer;
  return function(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => func.apply(this, args), delay);
  };
}




//深拷贝
export function deepClone(val : any) {
	return JSON.parse(JSON.stringify(val));
}



//手机号码 ****

export function getPhoneXXXX(phone : any) {
	if (!phone) return ''
	const reg = /(\d{3})\d{4}(\d{4})/;
	return phone.replace(reg, '$1****$2');
}

//输入金额
export function inputMoney(val : any) {

	val = val.replace(/(^\s*)|(\s*$)/g, "")

	var reg = /[^\d.]/g
	// 只能是数字和小数点，不能是其他输入
	val = val.replace(reg, "")
	// // 保证第一位只能是数字，不能是点
	val = val.replace(/^\./g, "");
	// // 小数只能出现1位
	val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
	// // 小数点后面保留2位
	val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');

	if (val.charAt(0) == '0' && val.length == 2 && val.charAt(1) != '.') {
		val = val.split('')
		val.shift()
		val = val.join('')
	}

	return val
}

export const getscrollviewheight=(id, instance)=> {
	return new Promise((resolve, reject) => {
		const { windowHeight } : any = uni.getSystemInfoSync() //获取设备的信息
		let query = uni.createSelectorQuery().in(instance);
		query.select(id).boundingClientRect((data : any) => {
			resolve(windowHeight - data.top)
		}).exec();
	})

}


export const getnavigationinfo = () => {
	const { statusBarHeight, windowWidth, windowHeight, platform, screenHeight,safeArea } : any = uni.getSystemInfoSync() //获取设备的信息
	//const { right, height, top } : any = uni.getMenuButtonBoundingClientRect()
	var navigationinfo = {
		windowHeight,
		state_height: statusBarHeight,
		state_width: windowWidth,
		allHeight: statusBarHeight * 2 + statusBarHeight,
		bottomheight: 0,
		platform,
		screenHeight
	}
	
	if (platform == "ios") {
		uni.getSystemInfoSync({
			success: function (res) {
				console.log('设备设备设备设备设备设备设备设备设备设备设备设备',res)
				let sHeight = res.screenHeight;//获取屏幕高度
				let sTop = res.safeArea.bottom;//获取安全区域底部高度
				navigationinfo.bottomheight = sHeight - sTop;//获取安全区域距离底部的高度

			}
		});

	}

	uni.setStorageSync('navigationinfo', navigationinfo)

}




export const openSetting = () => {//去开启定位权限
	return new Promise((resolve, reject) => {
		uni.openSetting({
			success: async function (res) {
				if (res.authSetting['scope.userLocation']) {//开启定位权限成功
					await getLocation()
					resolve(true)
				} else {
					reject(false)
				}
			}, fail(err) {//打开定位权限失败
				reject(false)
			}
		})
	})
}
export const getLocation = () => {//获取定位
	return new Promise((resolve, reject) => {
		uni.getLocation({
			type: 'gcj02',
			success(res) {//获取定位成功
				let userInfo = uni.getStorageSync('userInfo')
				let { latitude, longitude } = res
				userInfo.latitude = latitude
				userInfo.longitude = longitude
				userInfo.islocation = true//开启了定位权限
				uni.setStorageSync('userInfo', userInfo)
				store.state.userInfo = userInfo
				resolve(res)
			},
			fail(err) {//获取定位失败
				resolve(false)
			},
		})
	})
}



export const userLocation = () => {//是否开启定位权限
	return new Promise(async (resolve, reject) => {
		uni.authorize({
			scope: 'scope.userLocation',
			success: async function () {//开启了定位
				await getLocation()
				let userInfo = uni.getStorageSync('userInfo') || {}
				userInfo.islocation = true//开启了定位权限
				uni.setStorageSync('userInfo', userInfo)//拒绝开启定位	
				store.state.userInfo = userInfo
				resolve(true)
			},
			fail() {//没有开启定位
				let userInfo = uni.getStorageSync('userInfo') || {}
				userInfo.islocation = false//拒绝了定位权限
				userInfo.latitude = userInfo.latitude || 22.578341
				userInfo.longitude = userInfo.longitude || 114.116366
				uni.setStorageSync('userInfo', userInfo)//拒绝开启定位	
				store.state.userInfo = userInfo
				resolve(false)
			}
		})
	})
}

// 获取中文名的拼音首字母，并转换为大写
export const getPinyinFirstLetter = (name:any) => {
	// 正则表达式用于验证是否为大写的英文字母
	const isEnglishLetter = /^[A-Z]$/;
	if (!name) return '#'; // 如果名字为空，直接返回 '#'
    let pinyinArray = Pinyin.getShortPinyin(name, '');
	let initials = pinyinArray.split(' ').map((p:any) => p.charAt(0).toUpperCase()).join('');
    return isEnglishLetter.test(initials) ? initials : '#';
}
// 组合式函数，用于根据名字的拼音首字母对用户列表进行分组
export function useGroupUsersByPinyin(users:any,name:string) {
    const formattedUserList:any = ref([]);
	const grouped:any = {};

	users.forEach((user:any) => {
		const initial = getPinyinFirstLetter(name ? user[name] : user);
		if (!grouped[initial]) {
			grouped[initial] = [];
		}
		if(name){
			grouped[initial].push({
				...user,
				name: user[name]
			});
		}else{
			grouped[initial].push(user);
		}
		
	});
	formattedUserList.value = Object.keys(grouped)
		.sort() // 确保按字母顺序排序
		.map(letter => ({
			letter,
			userlist: grouped[letter]
		}));
	// 如果有 '#' 分类，确保它位于列表末尾
    if (grouped['#']) {
        formattedUserList.value.push(formattedUserList.value.shift());
    }
	return { formattedUserList };
}